/**
 * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 */

package com.library.slayer.service.persistence;

import com.library.slayer.NoSuchBookException;
import com.library.slayer.model.Book;
import com.library.slayer.model.impl.BookImpl;
import com.library.slayer.model.impl.BookModelImpl;

import com.liferay.portal.NoSuchModelException;
import com.liferay.portal.kernel.annotation.BeanReference;
import com.liferay.portal.kernel.cache.CacheRegistryUtil;
import com.liferay.portal.kernel.dao.orm.EntityCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderPath;
import com.liferay.portal.kernel.dao.orm.Query;
import com.liferay.portal.kernel.dao.orm.QueryPos;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.dao.orm.Session;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.InstanceFactory;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.ModelListener;
import com.liferay.portal.service.persistence.BatchSessionUtil;
import com.liferay.portal.service.persistence.ResourcePersistence;
import com.liferay.portal.service.persistence.UserPersistence;
import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;

import java.io.Serializable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * The persistence implementation for the book service.
 *
 * <p>
 * Never modify or reference this class directly. Always use {@link BookUtil} to access the book persistence. Modify <code>service.xml</code> and rerun ServiceBuilder to regenerate this class.
 * </p>
 *
 * <p>
 * Caching information and settings can be found in <code>portal.properties</code>
 * </p>
 *
 * @author Ahmed Hasan
 * @see BookPersistence
 * @see BookUtil
 * @generated
 */
public class BookPersistenceImpl extends BasePersistenceImpl<Book>
	implements BookPersistence {
	public static final String FINDER_CLASS_NAME_ENTITY = BookImpl.class.getName();
	public static final String FINDER_CLASS_NAME_LIST = FINDER_CLASS_NAME_ENTITY +
		".List";
	public static final FinderPath FINDER_PATH_FIND_BY_BOOKTITLE = new FinderPath(BookModelImpl.ENTITY_CACHE_ENABLED,
			BookModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
			"findByBookTitle",
			new String[] {
				String.class.getName(),
				
			"java.lang.Integer", "java.lang.Integer",
				"com.liferay.portal.kernel.util.OrderByComparator"
			});
	public static final FinderPath FINDER_PATH_COUNT_BY_BOOKTITLE = new FinderPath(BookModelImpl.ENTITY_CACHE_ENABLED,
			BookModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
			"countByBookTitle", new String[] { String.class.getName() });
	public static final FinderPath FINDER_PATH_FETCH_BY_BOOKTITLE_AUTHOR = new FinderPath(BookModelImpl.ENTITY_CACHE_ENABLED,
			BookModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_ENTITY,
			"fetchByBookTitle_Author",
			new String[] { String.class.getName(), String.class.getName() });
	public static final FinderPath FINDER_PATH_COUNT_BY_BOOKTITLE_AUTHOR = new FinderPath(BookModelImpl.ENTITY_CACHE_ENABLED,
			BookModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
			"countByBookTitle_Author",
			new String[] { String.class.getName(), String.class.getName() });
	public static final FinderPath FINDER_PATH_FIND_ALL = new FinderPath(BookModelImpl.ENTITY_CACHE_ENABLED,
			BookModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
			"findAll", new String[0]);
	public static final FinderPath FINDER_PATH_COUNT_ALL = new FinderPath(BookModelImpl.ENTITY_CACHE_ENABLED,
			BookModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
			"countAll", new String[0]);

	/**
	 * Caches the book in the entity cache if it is enabled.
	 *
	 * @param book the book to cache
	 */
	public void cacheResult(Book book) {
		EntityCacheUtil.putResult(BookModelImpl.ENTITY_CACHE_ENABLED,
			BookImpl.class, book.getPrimaryKey(), book);

		FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_BOOKTITLE_AUTHOR,
			new Object[] { book.getBookTitle(), book.getAuthor() }, book);
	}

	/**
	 * Caches the books in the entity cache if it is enabled.
	 *
	 * @param books the books to cache
	 */
	public void cacheResult(List<Book> books) {
		for (Book book : books) {
			if (EntityCacheUtil.getResult(BookModelImpl.ENTITY_CACHE_ENABLED,
						BookImpl.class, book.getPrimaryKey(), this) == null) {
				cacheResult(book);
			}
		}
	}

	/**
	 * Clears the cache for all books.
	 *
	 * <p>
	 * The {@link com.liferay.portal.kernel.dao.orm.EntityCache} and {@link com.liferay.portal.kernel.dao.orm.FinderCache} are both cleared by this method.
	 * </p>
	 */
	public void clearCache() {
		CacheRegistryUtil.clear(BookImpl.class.getName());
		EntityCacheUtil.clearCache(BookImpl.class.getName());
		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_ENTITY);
		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);
	}

	/**
	 * Clears the cache for the book.
	 *
	 * <p>
	 * The {@link com.liferay.portal.kernel.dao.orm.EntityCache} and {@link com.liferay.portal.kernel.dao.orm.FinderCache} are both cleared by this method.
	 * </p>
	 */
	public void clearCache(Book book) {
		EntityCacheUtil.removeResult(BookModelImpl.ENTITY_CACHE_ENABLED,
			BookImpl.class, book.getPrimaryKey());

		FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_BOOKTITLE_AUTHOR,
			new Object[] { book.getBookTitle(), book.getAuthor() });
	}

	/**
	 * Creates a new book with the primary key. Does not add the book to the database.
	 *
	 * @param bookId the primary key for the new book
	 * @return the new book
	 */
	public Book create(long bookId) {
		Book book = new BookImpl();

		book.setNew(true);
		book.setPrimaryKey(bookId);

		return book;
	}

	/**
	 * Removes the book with the primary key from the database. Also notifies the appropriate model listeners.
	 *
	 * @param primaryKey the primary key of the book to remove
	 * @return the book that was removed
	 * @throws com.liferay.portal.NoSuchModelException if a book with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Book remove(Serializable primaryKey)
		throws NoSuchModelException, SystemException {
		return remove(((Long)primaryKey).longValue());
	}

	/**
	 * Removes the book with the primary key from the database. Also notifies the appropriate model listeners.
	 *
	 * @param bookId the primary key of the book to remove
	 * @return the book that was removed
	 * @throws com.library.slayer.NoSuchBookException if a book with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Book remove(long bookId) throws NoSuchBookException, SystemException {
		Session session = null;

		try {
			session = openSession();

			Book book = (Book)session.get(BookImpl.class, new Long(bookId));

			if (book == null) {
				if (_log.isWarnEnabled()) {
					_log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + bookId);
				}

				throw new NoSuchBookException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
					bookId);
			}

			return remove(book);
		}
		catch (NoSuchBookException nsee) {
			throw nsee;
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}
	}

	protected Book removeImpl(Book book) throws SystemException {
		book = toUnwrappedModel(book);

		Session session = null;

		try {
			session = openSession();

			if (book.isCachedModel() || BatchSessionUtil.isEnabled()) {
				Object staleObject = session.get(BookImpl.class,
						book.getPrimaryKeyObj());

				if (staleObject != null) {
					session.evict(staleObject);
				}
			}

			session.delete(book);

			session.flush();
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}

		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);

		BookModelImpl bookModelImpl = (BookModelImpl)book;

		FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_BOOKTITLE_AUTHOR,
			new Object[] {
				bookModelImpl.getOriginalBookTitle(),
				
			bookModelImpl.getOriginalAuthor()
			});

		EntityCacheUtil.removeResult(BookModelImpl.ENTITY_CACHE_ENABLED,
			BookImpl.class, book.getPrimaryKey());

		return book;
	}

	public Book updateImpl(com.library.slayer.model.Book book, boolean merge)
		throws SystemException {
		book = toUnwrappedModel(book);

		boolean isNew = book.isNew();

		BookModelImpl bookModelImpl = (BookModelImpl)book;

		Session session = null;

		try {
			session = openSession();

			BatchSessionUtil.update(session, book, merge);

			book.setNew(false);
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}

		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);

		EntityCacheUtil.putResult(BookModelImpl.ENTITY_CACHE_ENABLED,
			BookImpl.class, book.getPrimaryKey(), book);

		if (!isNew &&
				(!Validator.equals(book.getBookTitle(),
					bookModelImpl.getOriginalBookTitle()) ||
				!Validator.equals(book.getAuthor(),
					bookModelImpl.getOriginalAuthor()))) {
			FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_BOOKTITLE_AUTHOR,
				new Object[] {
					bookModelImpl.getOriginalBookTitle(),
					
				bookModelImpl.getOriginalAuthor()
				});
		}

		if (isNew ||
				(!Validator.equals(book.getBookTitle(),
					bookModelImpl.getOriginalBookTitle()) ||
				!Validator.equals(book.getAuthor(),
					bookModelImpl.getOriginalAuthor()))) {
			FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_BOOKTITLE_AUTHOR,
				new Object[] { book.getBookTitle(), book.getAuthor() }, book);
		}

		return book;
	}

	protected Book toUnwrappedModel(Book book) {
		if (book instanceof BookImpl) {
			return book;
		}

		BookImpl bookImpl = new BookImpl();

		bookImpl.setNew(book.isNew());
		bookImpl.setPrimaryKey(book.getPrimaryKey());

		bookImpl.setBookId(book.getBookId());
		bookImpl.setBookTitle(book.getBookTitle());
		bookImpl.setAuthor(book.getAuthor());
		bookImpl.setDateAdded(book.getDateAdded());
		bookImpl.setDateModified(book.getDateModified());

		return bookImpl;
	}

	/**
	 * Finds the book with the primary key or throws a {@link com.liferay.portal.NoSuchModelException} if it could not be found.
	 *
	 * @param primaryKey the primary key of the book to find
	 * @return the book
	 * @throws com.liferay.portal.NoSuchModelException if a book with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Book findByPrimaryKey(Serializable primaryKey)
		throws NoSuchModelException, SystemException {
		return findByPrimaryKey(((Long)primaryKey).longValue());
	}

	/**
	 * Finds the book with the primary key or throws a {@link com.library.slayer.NoSuchBookException} if it could not be found.
	 *
	 * @param bookId the primary key of the book to find
	 * @return the book
	 * @throws com.library.slayer.NoSuchBookException if a book with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Book findByPrimaryKey(long bookId)
		throws NoSuchBookException, SystemException {
		Book book = fetchByPrimaryKey(bookId);

		if (book == null) {
			if (_log.isWarnEnabled()) {
				_log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + bookId);
			}

			throw new NoSuchBookException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
				bookId);
		}

		return book;
	}

	/**
	 * Finds the book with the primary key or returns <code>null</code> if it could not be found.
	 *
	 * @param primaryKey the primary key of the book to find
	 * @return the book, or <code>null</code> if a book with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Book fetchByPrimaryKey(Serializable primaryKey)
		throws SystemException {
		return fetchByPrimaryKey(((Long)primaryKey).longValue());
	}

	/**
	 * Finds the book with the primary key or returns <code>null</code> if it could not be found.
	 *
	 * @param bookId the primary key of the book to find
	 * @return the book, or <code>null</code> if a book with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Book fetchByPrimaryKey(long bookId) throws SystemException {
		Book book = (Book)EntityCacheUtil.getResult(BookModelImpl.ENTITY_CACHE_ENABLED,
				BookImpl.class, bookId, this);

		if (book == null) {
			Session session = null;

			try {
				session = openSession();

				book = (Book)session.get(BookImpl.class, new Long(bookId));
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (book != null) {
					cacheResult(book);
				}

				closeSession(session);
			}
		}

		return book;
	}

	/**
	 * Finds all the books where bookTitle = &#63;.
	 *
	 * @param bookTitle the book title to search with
	 * @return the matching books
	 * @throws SystemException if a system exception occurred
	 */
	public List<Book> findByBookTitle(String bookTitle)
		throws SystemException {
		return findByBookTitle(bookTitle, QueryUtil.ALL_POS, QueryUtil.ALL_POS,
			null);
	}

	/**
	 * Finds a range of all the books where bookTitle = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param bookTitle the book title to search with
	 * @param start the lower bound of the range of books to return
	 * @param end the upper bound of the range of books to return (not inclusive)
	 * @return the range of matching books
	 * @throws SystemException if a system exception occurred
	 */
	public List<Book> findByBookTitle(String bookTitle, int start, int end)
		throws SystemException {
		return findByBookTitle(bookTitle, start, end, null);
	}

	/**
	 * Finds an ordered range of all the books where bookTitle = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param bookTitle the book title to search with
	 * @param start the lower bound of the range of books to return
	 * @param end the upper bound of the range of books to return (not inclusive)
	 * @param orderByComparator the comparator to order the results by
	 * @return the ordered range of matching books
	 * @throws SystemException if a system exception occurred
	 */
	public List<Book> findByBookTitle(String bookTitle, int start, int end,
		OrderByComparator orderByComparator) throws SystemException {
		Object[] finderArgs = new Object[] {
				bookTitle,
				
				String.valueOf(start), String.valueOf(end),
				String.valueOf(orderByComparator)
			};

		List<Book> list = (List<Book>)FinderCacheUtil.getResult(FINDER_PATH_FIND_BY_BOOKTITLE,
				finderArgs, this);

		if (list == null) {
			Session session = null;

			try {
				session = openSession();

				StringBundler query = null;

				if (orderByComparator != null) {
					query = new StringBundler(3 +
							(orderByComparator.getOrderByFields().length * 3));
				}
				else {
					query = new StringBundler(3);
				}

				query.append(_SQL_SELECT_BOOK_WHERE);

				if (bookTitle == null) {
					query.append(_FINDER_COLUMN_BOOKTITLE_BOOKTITLE_1);
				}
				else {
					if (bookTitle.equals(StringPool.BLANK)) {
						query.append(_FINDER_COLUMN_BOOKTITLE_BOOKTITLE_3);
					}
					else {
						query.append(_FINDER_COLUMN_BOOKTITLE_BOOKTITLE_2);
					}
				}

				if (orderByComparator != null) {
					appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
						orderByComparator);
				}

				else {
					query.append(BookModelImpl.ORDER_BY_JPQL);
				}

				String sql = query.toString();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				if (bookTitle != null) {
					qPos.add(bookTitle);
				}

				list = (List<Book>)QueryUtil.list(q, getDialect(), start, end);
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (list == null) {
					list = new ArrayList<Book>();
				}

				cacheResult(list);

				FinderCacheUtil.putResult(FINDER_PATH_FIND_BY_BOOKTITLE,
					finderArgs, list);

				closeSession(session);
			}
		}

		return list;
	}

	/**
	 * Finds the first book in the ordered set where bookTitle = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param bookTitle the book title to search with
	 * @param orderByComparator the comparator to order the set by
	 * @return the first matching book
	 * @throws com.library.slayer.NoSuchBookException if a matching book could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Book findByBookTitle_First(String bookTitle,
		OrderByComparator orderByComparator)
		throws NoSuchBookException, SystemException {
		List<Book> list = findByBookTitle(bookTitle, 0, 1, orderByComparator);

		if (list.isEmpty()) {
			StringBundler msg = new StringBundler(4);

			msg.append(_NO_SUCH_ENTITY_WITH_KEY);

			msg.append("bookTitle=");
			msg.append(bookTitle);

			msg.append(StringPool.CLOSE_CURLY_BRACE);

			throw new NoSuchBookException(msg.toString());
		}
		else {
			return list.get(0);
		}
	}

	/**
	 * Finds the last book in the ordered set where bookTitle = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param bookTitle the book title to search with
	 * @param orderByComparator the comparator to order the set by
	 * @return the last matching book
	 * @throws com.library.slayer.NoSuchBookException if a matching book could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Book findByBookTitle_Last(String bookTitle,
		OrderByComparator orderByComparator)
		throws NoSuchBookException, SystemException {
		int count = countByBookTitle(bookTitle);

		List<Book> list = findByBookTitle(bookTitle, count - 1, count,
				orderByComparator);

		if (list.isEmpty()) {
			StringBundler msg = new StringBundler(4);

			msg.append(_NO_SUCH_ENTITY_WITH_KEY);

			msg.append("bookTitle=");
			msg.append(bookTitle);

			msg.append(StringPool.CLOSE_CURLY_BRACE);

			throw new NoSuchBookException(msg.toString());
		}
		else {
			return list.get(0);
		}
	}

	/**
	 * Finds the books before and after the current book in the ordered set where bookTitle = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param bookId the primary key of the current book
	 * @param bookTitle the book title to search with
	 * @param orderByComparator the comparator to order the set by
	 * @return the previous, current, and next book
	 * @throws com.library.slayer.NoSuchBookException if a book with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Book[] findByBookTitle_PrevAndNext(long bookId, String bookTitle,
		OrderByComparator orderByComparator)
		throws NoSuchBookException, SystemException {
		Book book = findByPrimaryKey(bookId);

		Session session = null;

		try {
			session = openSession();

			Book[] array = new BookImpl[3];

			array[0] = getByBookTitle_PrevAndNext(session, book, bookTitle,
					orderByComparator, true);

			array[1] = book;

			array[2] = getByBookTitle_PrevAndNext(session, book, bookTitle,
					orderByComparator, false);

			return array;
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}
	}

	protected Book getByBookTitle_PrevAndNext(Session session, Book book,
		String bookTitle, OrderByComparator orderByComparator, boolean previous) {
		StringBundler query = null;

		if (orderByComparator != null) {
			query = new StringBundler(6 +
					(orderByComparator.getOrderByFields().length * 6));
		}
		else {
			query = new StringBundler(3);
		}

		query.append(_SQL_SELECT_BOOK_WHERE);

		if (bookTitle == null) {
			query.append(_FINDER_COLUMN_BOOKTITLE_BOOKTITLE_1);
		}
		else {
			if (bookTitle.equals(StringPool.BLANK)) {
				query.append(_FINDER_COLUMN_BOOKTITLE_BOOKTITLE_3);
			}
			else {
				query.append(_FINDER_COLUMN_BOOKTITLE_BOOKTITLE_2);
			}
		}

		if (orderByComparator != null) {
			String[] orderByFields = orderByComparator.getOrderByFields();

			if (orderByFields.length > 0) {
				query.append(WHERE_AND);
			}

			for (int i = 0; i < orderByFields.length; i++) {
				query.append(_ORDER_BY_ENTITY_ALIAS);
				query.append(orderByFields[i]);

				if ((i + 1) < orderByFields.length) {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(WHERE_GREATER_THAN_HAS_NEXT);
					}
					else {
						query.append(WHERE_LESSER_THAN_HAS_NEXT);
					}
				}
				else {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(WHERE_GREATER_THAN);
					}
					else {
						query.append(WHERE_LESSER_THAN);
					}
				}
			}

			query.append(ORDER_BY_CLAUSE);

			for (int i = 0; i < orderByFields.length; i++) {
				query.append(_ORDER_BY_ENTITY_ALIAS);
				query.append(orderByFields[i]);

				if ((i + 1) < orderByFields.length) {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(ORDER_BY_ASC_HAS_NEXT);
					}
					else {
						query.append(ORDER_BY_DESC_HAS_NEXT);
					}
				}
				else {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(ORDER_BY_ASC);
					}
					else {
						query.append(ORDER_BY_DESC);
					}
				}
			}
		}

		else {
			query.append(BookModelImpl.ORDER_BY_JPQL);
		}

		String sql = query.toString();

		Query q = session.createQuery(sql);

		q.setFirstResult(0);
		q.setMaxResults(2);

		QueryPos qPos = QueryPos.getInstance(q);

		if (bookTitle != null) {
			qPos.add(bookTitle);
		}

		if (orderByComparator != null) {
			Object[] values = orderByComparator.getOrderByValues(book);

			for (Object value : values) {
				qPos.add(value);
			}
		}

		List<Book> list = q.list();

		if (list.size() == 2) {
			return list.get(1);
		}
		else {
			return null;
		}
	}

	/**
	 * Finds the book where bookTitle = &#63; and author = &#63; or throws a {@link com.library.slayer.NoSuchBookException} if it could not be found.
	 *
	 * @param bookTitle the book title to search with
	 * @param author the author to search with
	 * @return the matching book
	 * @throws com.library.slayer.NoSuchBookException if a matching book could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Book findByBookTitle_Author(String bookTitle, String author)
		throws NoSuchBookException, SystemException {
		Book book = fetchByBookTitle_Author(bookTitle, author);

		if (book == null) {
			StringBundler msg = new StringBundler(6);

			msg.append(_NO_SUCH_ENTITY_WITH_KEY);

			msg.append("bookTitle=");
			msg.append(bookTitle);

			msg.append(", author=");
			msg.append(author);

			msg.append(StringPool.CLOSE_CURLY_BRACE);

			if (_log.isWarnEnabled()) {
				_log.warn(msg.toString());
			}

			throw new NoSuchBookException(msg.toString());
		}

		return book;
	}

	/**
	 * Finds the book where bookTitle = &#63; and author = &#63; or returns <code>null</code> if it could not be found. Uses the finder cache.
	 *
	 * @param bookTitle the book title to search with
	 * @param author the author to search with
	 * @return the matching book, or <code>null</code> if a matching book could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Book fetchByBookTitle_Author(String bookTitle, String author)
		throws SystemException {
		return fetchByBookTitle_Author(bookTitle, author, true);
	}

	/**
	 * Finds the book where bookTitle = &#63; and author = &#63; or returns <code>null</code> if it could not be found, optionally using the finder cache.
	 *
	 * @param bookTitle the book title to search with
	 * @param author the author to search with
	 * @return the matching book, or <code>null</code> if a matching book could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Book fetchByBookTitle_Author(String bookTitle, String author,
		boolean retrieveFromCache) throws SystemException {
		Object[] finderArgs = new Object[] { bookTitle, author };

		Object result = null;

		if (retrieveFromCache) {
			result = FinderCacheUtil.getResult(FINDER_PATH_FETCH_BY_BOOKTITLE_AUTHOR,
					finderArgs, this);
		}

		if (result == null) {
			Session session = null;

			try {
				session = openSession();

				StringBundler query = new StringBundler(4);

				query.append(_SQL_SELECT_BOOK_WHERE);

				if (bookTitle == null) {
					query.append(_FINDER_COLUMN_BOOKTITLE_AUTHOR_BOOKTITLE_1);
				}
				else {
					if (bookTitle.equals(StringPool.BLANK)) {
						query.append(_FINDER_COLUMN_BOOKTITLE_AUTHOR_BOOKTITLE_3);
					}
					else {
						query.append(_FINDER_COLUMN_BOOKTITLE_AUTHOR_BOOKTITLE_2);
					}
				}

				if (author == null) {
					query.append(_FINDER_COLUMN_BOOKTITLE_AUTHOR_AUTHOR_1);
				}
				else {
					if (author.equals(StringPool.BLANK)) {
						query.append(_FINDER_COLUMN_BOOKTITLE_AUTHOR_AUTHOR_3);
					}
					else {
						query.append(_FINDER_COLUMN_BOOKTITLE_AUTHOR_AUTHOR_2);
					}
				}

				query.append(BookModelImpl.ORDER_BY_JPQL);

				String sql = query.toString();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				if (bookTitle != null) {
					qPos.add(bookTitle);
				}

				if (author != null) {
					qPos.add(author);
				}

				List<Book> list = q.list();

				result = list;

				Book book = null;

				if (list.isEmpty()) {
					FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_BOOKTITLE_AUTHOR,
						finderArgs, list);
				}
				else {
					book = list.get(0);

					cacheResult(book);

					if ((book.getBookTitle() == null) ||
							!book.getBookTitle().equals(bookTitle) ||
							(book.getAuthor() == null) ||
							!book.getAuthor().equals(author)) {
						FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_BOOKTITLE_AUTHOR,
							finderArgs, book);
					}
				}

				return book;
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (result == null) {
					FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_BOOKTITLE_AUTHOR,
						finderArgs, new ArrayList<Book>());
				}

				closeSession(session);
			}
		}
		else {
			if (result instanceof List<?>) {
				return null;
			}
			else {
				return (Book)result;
			}
		}
	}

	/**
	 * Finds all the books.
	 *
	 * @return the books
	 * @throws SystemException if a system exception occurred
	 */
	public List<Book> findAll() throws SystemException {
		return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
	}

	/**
	 * Finds a range of all the books.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param start the lower bound of the range of books to return
	 * @param end the upper bound of the range of books to return (not inclusive)
	 * @return the range of books
	 * @throws SystemException if a system exception occurred
	 */
	public List<Book> findAll(int start, int end) throws SystemException {
		return findAll(start, end, null);
	}

	/**
	 * Finds an ordered range of all the books.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param start the lower bound of the range of books to return
	 * @param end the upper bound of the range of books to return (not inclusive)
	 * @param orderByComparator the comparator to order the results by
	 * @return the ordered range of books
	 * @throws SystemException if a system exception occurred
	 */
	public List<Book> findAll(int start, int end,
		OrderByComparator orderByComparator) throws SystemException {
		Object[] finderArgs = new Object[] {
				String.valueOf(start), String.valueOf(end),
				String.valueOf(orderByComparator)
			};

		List<Book> list = (List<Book>)FinderCacheUtil.getResult(FINDER_PATH_FIND_ALL,
				finderArgs, this);

		if (list == null) {
			Session session = null;

			try {
				session = openSession();

				StringBundler query = null;
				String sql = null;

				if (orderByComparator != null) {
					query = new StringBundler(2 +
							(orderByComparator.getOrderByFields().length * 3));

					query.append(_SQL_SELECT_BOOK);

					appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
						orderByComparator);

					sql = query.toString();
				}
				else {
					sql = _SQL_SELECT_BOOK.concat(BookModelImpl.ORDER_BY_JPQL);
				}

				Query q = session.createQuery(sql);

				if (orderByComparator == null) {
					list = (List<Book>)QueryUtil.list(q, getDialect(), start,
							end, false);

					Collections.sort(list);
				}
				else {
					list = (List<Book>)QueryUtil.list(q, getDialect(), start,
							end);
				}
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (list == null) {
					list = new ArrayList<Book>();
				}

				cacheResult(list);

				FinderCacheUtil.putResult(FINDER_PATH_FIND_ALL, finderArgs, list);

				closeSession(session);
			}
		}

		return list;
	}

	/**
	 * Removes all the books where bookTitle = &#63; from the database.
	 *
	 * @param bookTitle the book title to search with
	 * @throws SystemException if a system exception occurred
	 */
	public void removeByBookTitle(String bookTitle) throws SystemException {
		for (Book book : findByBookTitle(bookTitle)) {
			remove(book);
		}
	}

	/**
	 * Removes the book where bookTitle = &#63; and author = &#63; from the database.
	 *
	 * @param bookTitle the book title to search with
	 * @param author the author to search with
	 * @throws SystemException if a system exception occurred
	 */
	public void removeByBookTitle_Author(String bookTitle, String author)
		throws NoSuchBookException, SystemException {
		Book book = findByBookTitle_Author(bookTitle, author);

		remove(book);
	}

	/**
	 * Removes all the books from the database.
	 *
	 * @throws SystemException if a system exception occurred
	 */
	public void removeAll() throws SystemException {
		for (Book book : findAll()) {
			remove(book);
		}
	}

	/**
	 * Counts all the books where bookTitle = &#63;.
	 *
	 * @param bookTitle the book title to search with
	 * @return the number of matching books
	 * @throws SystemException if a system exception occurred
	 */
	public int countByBookTitle(String bookTitle) throws SystemException {
		Object[] finderArgs = new Object[] { bookTitle };

		Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_BY_BOOKTITLE,
				finderArgs, this);

		if (count == null) {
			Session session = null;

			try {
				session = openSession();

				StringBundler query = new StringBundler(2);

				query.append(_SQL_COUNT_BOOK_WHERE);

				if (bookTitle == null) {
					query.append(_FINDER_COLUMN_BOOKTITLE_BOOKTITLE_1);
				}
				else {
					if (bookTitle.equals(StringPool.BLANK)) {
						query.append(_FINDER_COLUMN_BOOKTITLE_BOOKTITLE_3);
					}
					else {
						query.append(_FINDER_COLUMN_BOOKTITLE_BOOKTITLE_2);
					}
				}

				String sql = query.toString();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				if (bookTitle != null) {
					qPos.add(bookTitle);
				}

				count = (Long)q.uniqueResult();
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (count == null) {
					count = Long.valueOf(0);
				}

				FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_BOOKTITLE,
					finderArgs, count);

				closeSession(session);
			}
		}

		return count.intValue();
	}

	/**
	 * Counts all the books where bookTitle = &#63; and author = &#63;.
	 *
	 * @param bookTitle the book title to search with
	 * @param author the author to search with
	 * @return the number of matching books
	 * @throws SystemException if a system exception occurred
	 */
	public int countByBookTitle_Author(String bookTitle, String author)
		throws SystemException {
		Object[] finderArgs = new Object[] { bookTitle, author };

		Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_BY_BOOKTITLE_AUTHOR,
				finderArgs, this);

		if (count == null) {
			Session session = null;

			try {
				session = openSession();

				StringBundler query = new StringBundler(3);

				query.append(_SQL_COUNT_BOOK_WHERE);

				if (bookTitle == null) {
					query.append(_FINDER_COLUMN_BOOKTITLE_AUTHOR_BOOKTITLE_1);
				}
				else {
					if (bookTitle.equals(StringPool.BLANK)) {
						query.append(_FINDER_COLUMN_BOOKTITLE_AUTHOR_BOOKTITLE_3);
					}
					else {
						query.append(_FINDER_COLUMN_BOOKTITLE_AUTHOR_BOOKTITLE_2);
					}
				}

				if (author == null) {
					query.append(_FINDER_COLUMN_BOOKTITLE_AUTHOR_AUTHOR_1);
				}
				else {
					if (author.equals(StringPool.BLANK)) {
						query.append(_FINDER_COLUMN_BOOKTITLE_AUTHOR_AUTHOR_3);
					}
					else {
						query.append(_FINDER_COLUMN_BOOKTITLE_AUTHOR_AUTHOR_2);
					}
				}

				String sql = query.toString();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				if (bookTitle != null) {
					qPos.add(bookTitle);
				}

				if (author != null) {
					qPos.add(author);
				}

				count = (Long)q.uniqueResult();
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (count == null) {
					count = Long.valueOf(0);
				}

				FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_BOOKTITLE_AUTHOR,
					finderArgs, count);

				closeSession(session);
			}
		}

		return count.intValue();
	}

	/**
	 * Counts all the books.
	 *
	 * @return the number of books
	 * @throws SystemException if a system exception occurred
	 */
	public int countAll() throws SystemException {
		Object[] finderArgs = new Object[0];

		Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_ALL,
				finderArgs, this);

		if (count == null) {
			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(_SQL_COUNT_BOOK);

				count = (Long)q.uniqueResult();
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (count == null) {
					count = Long.valueOf(0);
				}

				FinderCacheUtil.putResult(FINDER_PATH_COUNT_ALL, finderArgs,
					count);

				closeSession(session);
			}
		}

		return count.intValue();
	}

	/**
	 * Initializes the book persistence.
	 */
	public void afterPropertiesSet() {
		String[] listenerClassNames = StringUtil.split(GetterUtil.getString(
					com.liferay.util.service.ServiceProps.get(
						"value.object.listener.com.library.slayer.model.Book")));

		if (listenerClassNames.length > 0) {
			try {
				List<ModelListener<Book>> listenersList = new ArrayList<ModelListener<Book>>();

				for (String listenerClassName : listenerClassNames) {
					listenersList.add((ModelListener<Book>)InstanceFactory.newInstance(
							listenerClassName));
				}

				listeners = listenersList.toArray(new ModelListener[listenersList.size()]);
			}
			catch (Exception e) {
				_log.error(e);
			}
		}
	}

	@BeanReference(type = BookPersistence.class)
	protected BookPersistence bookPersistence;
	@BeanReference(type = ResourcePersistence.class)
	protected ResourcePersistence resourcePersistence;
	@BeanReference(type = UserPersistence.class)
	protected UserPersistence userPersistence;
	private static final String _SQL_SELECT_BOOK = "SELECT book FROM Book book";
	private static final String _SQL_SELECT_BOOK_WHERE = "SELECT book FROM Book book WHERE ";
	private static final String _SQL_COUNT_BOOK = "SELECT COUNT(book) FROM Book book";
	private static final String _SQL_COUNT_BOOK_WHERE = "SELECT COUNT(book) FROM Book book WHERE ";
	private static final String _FINDER_COLUMN_BOOKTITLE_BOOKTITLE_1 = "book.bookTitle IS NULL";
	private static final String _FINDER_COLUMN_BOOKTITLE_BOOKTITLE_2 = "book.bookTitle = ?";
	private static final String _FINDER_COLUMN_BOOKTITLE_BOOKTITLE_3 = "(book.bookTitle IS NULL OR book.bookTitle = ?)";
	private static final String _FINDER_COLUMN_BOOKTITLE_AUTHOR_BOOKTITLE_1 = "book.bookTitle IS NULL AND ";
	private static final String _FINDER_COLUMN_BOOKTITLE_AUTHOR_BOOKTITLE_2 = "book.bookTitle = ? AND ";
	private static final String _FINDER_COLUMN_BOOKTITLE_AUTHOR_BOOKTITLE_3 = "(book.bookTitle IS NULL OR book.bookTitle = ?) AND ";
	private static final String _FINDER_COLUMN_BOOKTITLE_AUTHOR_AUTHOR_1 = "book.author IS NULL";
	private static final String _FINDER_COLUMN_BOOKTITLE_AUTHOR_AUTHOR_2 = "book.author = ?";
	private static final String _FINDER_COLUMN_BOOKTITLE_AUTHOR_AUTHOR_3 = "(book.author IS NULL OR book.author = ?)";
	private static final String _ORDER_BY_ENTITY_ALIAS = "book.";
	private static final String _NO_SUCH_ENTITY_WITH_PRIMARY_KEY = "No Book exists with the primary key ";
	private static final String _NO_SUCH_ENTITY_WITH_KEY = "No Book exists with the key {";
	private static Log _log = LogFactoryUtil.getLog(BookPersistenceImpl.class);
}